package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Mahone
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;

    /**
     * 图片文件上传接口：将图片上传到MinIO返回图片上传地址
     * @param file 上传文件
     * @return 在线地址
     */
    @Override
    public String fileUpload(MultipartFile file) {
        // 1.判断文件是否为图片
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null){
                throw new GuiguException(ResultCodeEnum.PHOTO_UPLOAD_ERROR);
            }
            // 2.调用MinIO对象将图片上传到MinIO
            // 2.1 生成随机的文件名称 避免文件同名
            String today = DateUtil.today();
            String fileName = IdUtil.randomUUID();
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            String objectName = "/" + today + "/" + fileName + "." + extName;
            // 2.2 上传到MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(props.getBucketName())
                            .object(objectName)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .contentType(file.getContentType())
                            .build());
            // 3.拼接上传后的文件的url地址:http://192.168.200.6:9000/test/2024-02-21/lrq.jpg
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("[专辑服务]图片文件上传异常：{}",e);
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

    }
}
